<template>
  <div class="home">
    <div class="header">
      <div class="logo"></div>
      <div class="titleMain">
        <h1>全流程成材率模型主页</h1>
      </div>
    </div>
    <div class="common-layout linear-gradient">
      <el-container>
        <!-- <div>
          <el-button style="margin-top: -9vh; margin-left: 94vw" type="primary" @click="drawer2 = true">目录</el-button>
        </div> -->
        <el-header>
          <div class="top">
            <div class="msg-title">未完成原因</div>
            <div class="information">
              <div class="left-content">
                <el-text style="color: #fff">{{ unCompleteReason }}</el-text>
              </div>
              <div class="right-content">
                <el-select v-model="teamDateType" placeholder="时间范围" style="width: 100px" @change="dateChange('team', teamDateType)">
                  <el-option v-for="item in dateTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <el-date-picker
                  v-model="dateRange"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期时间"
                  end-placeholder="结束日期时间"
                  class="custom-date-picker"
                  size="small"
                  @change="handleDateRangeChange"
                />
                <span class="label">产线:</span>
                <el-select
                  v-model="searchParams.prodLine"
                  placeholder="全部"
                  clearable
                  size="small"
                  class="custom-select"
                  style="width: 150px"
                  @change="onProdLineChange"
                >
                  <el-option label="连退1630" value="cal1630" />
                  <el-option label="连退2150" value="cal2150" />
                  <el-option label="镀锌1870" value="cgl1870" />
                  <el-option label="酸轧2280" value="tcm2280" />
                  <el-option label="重卷1630" value="rcl1630" />
                  <el-option label="重卷2150" value="rcl2150" />
                  <el-option label="重卷1870" value="rcl1870" />
                </el-select>
              </div>
            </div>
          </div>
        </el-header>
        <el-main class="main-container">
          <el-row>
            <div class="card-container" style="margin-right: 1%">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span class="card-title">总成材率</span>
                  </div>
                </template>
                <div style="width: 100%; height: 220px">
                  <div ref="treeChartRef" style="width: 100%; height: 100%"></div>
                </div>
              </el-card>
            </div>
            <div class="card-container">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <el-tooltip effect="dark" :content="title">
                      <span class="card-title overText">{{ title }}</span>
                    </el-tooltip>
                  </div>
                </template>
                <div class="card-body lossAnalysis">
                  <el-table
                    size="small"
                    :data="lossAnalysisTableData"
                    style="width: 100%"
                    max-height="26vh"
                    :header-cell-style="{ background: '#2f59af', color: '#fff', textAlign: 'center' }"
                    @row-click="handleProductTypeRowClick"
                    :cell-style="{
                      color: '#fff',
                      textAlign: 'center',
                      height: '3vh',
                      border: '1px solid #ebeef5',
                    }"
                    show-overflow-tooltip
                    :span-method="spanFunc"
                  >
                    <el-table-column prop="process" label="工序" width="80" />
                    <el-table-column prop="line" label="机组" width="100" />
                    <el-table-column prop="factor" label="影响成材率因素" />
                    <!-- <el-table-column prop="requirement" label="工艺要求标准" width="160" /> -->
                    <el-table-column prop="target" label="理论值[吨]" width="120" />
                    <el-table-column prop="realvalue" label="本期实际[吨]" width="120" />
                    <el-table-column prop="loss" label="损失重量[吨]" width="120" />
                    <el-table-column prop="prorate" label="影响成材率指标（%）" width="190" />
                  </el-table>
                  <!-- <div class="table-container">
                    <el-table
                      size="small"
                      :data="steelGradeTableData"
                      style="width: 100%"
                      max-height="160"
                      :header-cell-style="{ background: '#2f59af', color: '#fff', textAlign: 'center' }"
                      @row-click="handleProductTypeRowClick"
                      :cell-style="{ color: '#fff', textAlign: 'center', height: '3vh' }"
                    >
                      <el-table-column prop="producttype" label="产品品类" show-overflow-tooltip />
                      <el-table-column prop="rate" label="损失比%" show-overflow-tooltip>
                        <template #default="scope">
                          <span>{{ scope.row.rate !== undefined && scope.row.rate !== null ? (Number(scope.row.rate) * 100).toFixed(2) : '-' }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="targetvalue" label="目标值%" show-overflow-tooltip />
                      <el-table-column prop="realvalue" label="实际值%" show-overflow-tooltip />
                    </el-table>
                    <div class="steel-grade-pagination-container">
                      <el-pagination
                        v-model:current-page="steelGradeCurrentPage"
                        v-model:page-size="steelGradePageSize"
                        :page-sizes="[5, 10, 20, 50]"
                        :total="steelGradeTotalCount"
                        layout="total, sizes, prev, pager, next, jumper"
                        background
                        :pager-count="3"
                        small
                        @size-change="handleSteelGradeSizeChange"
                        @current-change="handleSteelGradeCurrentChange"
                      />
                    </div>
                  </div> -->
                  <!-- <div class="graph-container">
                    <graph-pie :data="steelGradeGraphData"></graph-pie>
                  </div> -->
                </div>
              </el-card>
            </div>
          </el-row>
          <el-row style="margin-top: 20px">
            <div class="card-container" style="margin-right: 1%">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span class="card-title">机组计算成材率</span>
                  </div>
                </template>
                <div class="card-body">
                  <div class="table-container">
                    <el-table
                      size="small"
                      :data="teamTableData"
                      style="width: 100%"
                      max-height="160"
                      :header-cell-style="{ background: '#2f59af', color: '#fff', textAlign: 'center' }"
                      :cell-style="{ color: '#fff', textAlign: 'center', height: '3vh' }"
                      @row-click="handleTeamRowClick"
                      @row-mouseenter="handleTeamRowMouseEnter"
                      @row-mouseleave="handleTeamRowMouseLeave"
                      :row-class-name="teamRowClassName"
                      highlight-current-row
                      :current-row="currentTeamRow"
                    >
                      <el-table-column prop="linename" label="机组" show-overflow-tooltip />
                      <el-table-column prop="rate" label="损失比%" show-overflow-tooltip>
                        <template #default="scope">
                          <span>{{ scope.row.rate !== undefined && scope.row.rate !== null ? scope.row.rate : '-' }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="targetvalue" label="目标值%" show-overflow-tooltip />
                      <el-table-column prop="realvalue" label="实际值%" show-overflow-tooltip />
                    </el-table>
                    <!-- 机组计算成材率分页 -->
                    <div class="team-pagination-container">
                      <el-pagination
                        v-model:current-page="teamCurrentPage"
                        v-model:page-size="teamPageSize"
                        :page-sizes="[5, 10, 20, 50]"
                        :total="teamTotalCount"
                        layout="total, sizes, prev, pager, next, jumper"
                        background
                        small
                        @size-change="handleTeamSizeChange"
                        @current-change="handleTeamCurrentChange"
                      />
                    </div>
                  </div>
                  <div class="graph-container">
                    <graph-pie :data="teamGraphData" @pie-click="handlePieClick"></graph-pie>
                  </div>
                </div>
              </el-card>
            </div>
            <div class="card-container">
              <el-card>
                <!-- <template #header>
                  <div class="card-header">
                    <span class="card-title">异常原因</span>
                  </div>
                </template> -->
                <div class="card-body">
                  <el-tabs v-model="activeReasonTab" type="card" @tab-click="handleReasonTabClick">
                    <el-tab-pane label="异常原因" name="reason">
                      <div class="table-container">
                        <el-table
                          size="small"
                          :data="reasonTableData"
                          style="width: 100%"
                          max-height="160"
                          :header-cell-style="{ background: '#2f59af', color: '#fff', textAlign: 'center' }"
                          :cell-style="{ color: '#fff', textAlign: 'center', height: '3vh' }"
                          @row-click="handleReasonRowClick"
                        >
                          <el-table-column prop="uncompletereason" label="原因" show-overflow-tooltip />
                          <el-table-column prop="rate" label="损失比%" show-overflow-tooltip>
                            <template #default="scope">
                              <span>{{ scope.row.rate !== undefined && scope.row.rate !== null ? Number(scope.row.rate).toFixed(2) : '-' }}</span>
                            </template>
                          </el-table-column>
                          <el-table-column prop="targetvalue" label="目标值%" show-overflow-tooltip />
                          <el-table-column prop="realvalue" label="实际值%" show-overflow-tooltip />
                        </el-table>
                        <div class="reason-pagination-container">
                          <el-pagination
                            v-model:current-page="reasonCurrentPage"
                            v-model:page-size="reasonPageSize"
                            :page-sizes="[5, 10, 20, 50]"
                            :total="reasonTotalCount"
                            layout="total, sizes, prev, pager, next, jumper"
                            background
                            small
                            :pager-count="3"
                            @size-change="handleReasonSizeChange"
                            @current-change="handleReasonCurrentChange"
                          />
                        </div>
                      </div>
                    </el-tab-pane>

                    <el-tab-pane label="产品品类异常原因" name="productReason">
                      <div class="table-container product-reason-wrap">
                        <div class="table-scroll-x">
                          <el-table
                            size="small"
                            :data="productTableData"
                            style="width: 100%"
                            max-height="160"
                            :header-cell-style="{ background: '#2f59af', color: '#fff', textAlign: 'center' }"
                            @row-click="handleProductReasonRowClick"
                            :cell-style="{ color: '#fff', textAlign: 'center', height: '3vh' }"
                          >
                            <el-table-column prop="uncompletereason" label="原因" show-overflow-tooltip />
                            <el-table-column prop="producttype" label="产品品类" show-overflow-tooltip />
                            <el-table-column prop="targetvalue" label="目标值%" show-overflow-tooltip />
                            <el-table-column prop="realvalue" label="实际值%" show-overflow-tooltip />
                            <el-table-column prop="rate" label="损失比%" show-overflow-tooltip>
                              <template #default="scope">
                                <span>{{ scope.row.rate !== undefined && scope.row.rate !== null ? Number(scope.row.rate).toFixed(2) : '-' }}</span>
                              </template>
                            </el-table-column>
                          </el-table>
                        </div>
                        <div class="reason-pagination-container">
                          <el-pagination
                            v-model:current-page="productReasonCurrentPage"
                            v-model:page-size="productReasonPageSize"
                            :page-sizes="[5, 10, 20, 50]"
                            :total="productReasonTotalCount"
                            layout="total, sizes, prev, pager, next, jumper"
                            background
                            small
                            :pager-count="3"
                            @size-change="handleProductReasonSizeChange"
                            @current-change="handleProductReasonCurrentChange"
                          />
                        </div>
                      </div>
                    </el-tab-pane>
                    <el-tab-pane label="质量缺陷" name="qualityDefect">
                      <div class="q-table-container product-reason-wrap" v-if="activeReasonTab == 'qualityDefect'">
                        <div class="table-scroll-x">
                          <el-table
                            size="small"
                            :data="qualityDefectTableData"
                            style="width: 100%"
                            max-height="160"
                            :header-cell-style="{ background: '#2f59af', color: '#fff', textAlign: 'center' }"
                            @row-click="openDetail"
                            :cell-style="{ color: '#fff', textAlign: 'center', height: '3vh' }"
                          >
                            <el-table-column prop="exwt" label="入口重量[kg]" show-overflow-tooltip width="120px" />
                            <el-table-column prop="rcltotalexwt" label="重卷出口重量[kg]" show-overflow-tooltip width="150px" />
                            <el-table-column prop="lostweight" label="重量损失[kg]" show-overflow-tooltip width="120px" />
                            <el-table-column prop="defectclass" label="缺陷等级" show-overflow-tooltip width="90px" />
                            <el-table-column prop="defectattributioncode" label="缺陷归户" show-overflow-tooltip width="90px" />
                          </el-table>
                        </div>
                        <div class="reason-pagination-container">
                          <el-pagination
                            v-model:current-page="qualityDefectCurrentPage"
                            v-model:page-size="qualityDefectPageSize"
                            :page-sizes="[5, 10, 20, 50]"
                            :total="qualityDefectTotalCount"
                            layout="total, sizes, prev, pager, next, jumper"
                            background
                            small
                            :pager-count="3"
                            @size-change="handleQualityDefectSizeChange"
                            @current-change="handleQualityDefectCurrentChange"
                          />
                        </div>
                      </div>
                    </el-tab-pane>
                  </el-tabs>

                  <div class="graph-container">
                    <graph-pie :data="currentReasonPieData"></graph-pie>
                  </div>
                </div>
              </el-card>
            </div>
          </el-row>
          <!-- <div class="pagination-container" style="width:100%;display:flex;justify-content:center;margin-top:20px;">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50]"
              :total="totalCount"
              layout="total, sizes, prev, pager, next, jumper"
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div> -->
        </el-main>
      </el-container>
    </div>
  </div>

  <!-- <el-drawer
    v-model="drawer2"
    title="分卷优化"
    :direction="direction"
    :before-close="drawerClose"
    style="background-image: linear-gradient(to top, white, '#2772d4') !important"
  >
  </el-drawer> -->
</template>
<script setup lang="ts">
  import { ref, reactive, computed, onMounted, onUnmounted, nextTick, defineComponent, watch, onBeforeMount } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import GraphPie from './GraphPie.vue';
  import * as echarts from 'echarts';
  import { api } from '/@/api/VolumeDivisionOptimization/index';
  import { useUserStore } from '/@/store/modules/system/user';
  import { ActualPerformanceRollDeviationApi } from '/@/api/deviationanalysis/ActualPerformanceRollDeviation';
  import { useRouter } from 'vue-router';
  import type { TabsPaneContext } from 'element-plus';
  import { fa, pa } from 'element-plus/es/locale';

  const data = ref([
    { menuName: 'FullProcessYieldRate', menuTitle: '全流程成材率主页', menuId: '1' },
    { menuName: 'FullprocessYieldNew', menuTitle: '新主页' },
    { menuName: 'FullprocessYield', menuTitle: '单产线成材率分析画面' },
    { menuName: 'CalculationOfYieldRate', menuTitle: '各产线全流程成材率计算及人工录入' },
    { menuName: 'DefectYieldAnalysis', menuTitle: '产品成材率全流程分析' },
    { menuName: 'CurrenSituationLossesOptimization', menuTitle: '成材率分档数据统计' },
    { menuName: 'HotRollingWidthAllowance', menuTitle: '热轧宽度余量统计分析' },
    { menuName: 'HotRollingReductionAmount', menuTitle: '热轧缩径量规格统计' },
    { menuName: 'qualityDefect', menuTitle: '质量缺陷明细' },
    { menuName: 'OtherFullprocessYield', menuTitle: '其他页面留存' },
  ]);

  interface SpecificationTableData {
    width: string;
    thickness: string;
    weight: string;
    totalLossWeight: string;
  }

  interface SteelGradeTableData {
    steelGrade: string;
    lossWeight: string;
    targetValue?: string;
    actualValue?: string;
  }

  interface TeamTableData {
    team: string;
    lossWeight: string;
    targetValue?: string;
    actualValue?: string;
  }

  interface ReasonTableData {
    uncompletereason: string;
    rate: string;
    targetvalue?: string;
    realvalue?: string;
    reason?: string; // 添加reason字段以兼容现有数据
    lossWeight?: string; // 添加lossWeight字段以兼容现有数据
    targetValue?: string; // 添加targetValue字段以兼容现有数据
    actualValue?: string; // 添加actualValue字段以兼容现有数据
  }

  interface tableDataGroup {
    specification: SpecificationTableData[];
    steelGrade: SteelGradeTableData[];
    team: TeamTableData[];
    reason: ReasonTableData[];
  }

  // --- Interfaces ---
  interface SearchParams {
    prodLine: string;
  }

  // 下拉框选项
  const dateTypeOptions = ref([
    { value: 'day', label: '日' },
    { value: 'week', label: '周' },
    { value: 'month', label: '月' },
  ]);

  const speDateType = ref('week');
  const steelDateType = ref('week');
  const teamDateType = ref('week');
  const reasonDateType = ref('week');
  const dateRange = ref<[Date, Date] | null>(null);
  const searchParams = reactive<SearchParams>({
    prodLine: 'tcm2280',
  });

  const steelGradeGraphData = ref<any[]>([]);

  const teamGraphData = ref<any[]>([]);

  const reasonGraphData = ref<any[]>([]);

  const productReasonGraphData = ref<any[]>([]);

  const specificationTableData = ref<any[]>([]);

  const steelGradeTableData = ref<any[]>([]);

  const productTableData = ref<any[]>([]);

  const teamTableData = ref<any[]>([]);

  const reasonTableData = ref<any[]>([]);

  const unCompleteReason = ref<string>('');
  const totalYield = ref<any>([]);

  const tableDataGroup = reactive<tableDataGroup>({
    specification: [
      { width: '0.1-0.2', thickness: '0.1-0.2', weight: '0.1-0.2', totalLossWeight: '120' },
      { width: '0.2-0.3', thickness: '0.1-0.2', weight: '0.1-0.2', totalLossWeight: '140' },
      { width: '0.3-0.4', thickness: '0.1-0.2', weight: '0.1-0.2', totalLossWeight: '160' },
      { width: '0.4-0.5', thickness: '0.1-0.2', weight: '0.1-0.2', totalLossWeight: '180' },
    ],
    steelGrade: [
      { steelGrade: 'SPEC', lossWeight: '220', targetValue: '230', actualValue: '225' },
      { steelGrade: 'SPET', lossWeight: '240', targetValue: '250', actualValue: '245' },
      { steelGrade: 'SPEC-H', lossWeight: '260', targetValue: '270', actualValue: '265' },
      { steelGrade: 'SPED', lossWeight: '280', targetValue: '290', actualValue: '285' },
    ],
    team: [
      { team: '班组1', lossWeight: '330', targetValue: '340', actualValue: '335' },
      { team: '班组2', lossWeight: '360', targetValue: '370', actualValue: '365' },
      { team: '班组3', lossWeight: '390', targetValue: '400', actualValue: '395' },
      { team: '班组4', lossWeight: '300', targetValue: '310', actualValue: '305' },
    ],
    reason: [
      { uncompletereason: '切尾异常', rate: '3.20', targetvalue: '3.30', realvalue: '3.25' },
      { uncompletereason: '切头异常', rate: '3.50', targetvalue: '3.60', realvalue: '3.55' },
      { uncompletereason: '温度异常', rate: '3.80', targetvalue: '3.90', realvalue: '3.85' },
      { uncompletereason: '操作异常', rate: '3.00', targetvalue: '3.10', realvalue: '3.05' },
    ],
  });

  const currentPage = ref(1);
  const pageSize = ref(10);
  const totalCount = ref(0);

  // 异常原因分页相关
  const reasonCurrentPage = ref(1);
  const reasonPageSize = ref(5);
  const reasonTotalCount = ref(0);

  // 机组计算成材率分页相关
  const teamCurrentPage = ref(1);
  const teamPageSize = ref(5);
  const teamTotalCount = ref(0);

  // 产品品类分页相关
  const steelGradeCurrentPage = ref(1);
  const steelGradePageSize = ref(5);
  const steelGradeTotalCount = ref(0);

  const productReasonCurrentPage = ref(1);
  const productReasonPageSize = ref(5);
  const productReasonTotalCount = ref(0);

  const router = useRouter();

  const currentTeamRow = ref(null);
  const hoverTeamRow = ref(null);

  const totalYieldAll = computed(() => (Array.isArray(totalYield.value) ? totalYield.value.find((item: any) => item.linename == 'all') : null));
  const coldYield = computed(() => (Array.isArray(totalYield.value) ? totalYield.value.find((item: any) => item.linename == 'cal') : null));
  const cglYield = computed(() => (Array.isArray(totalYield.value) ? totalYield.value.find((item: any) => item.linename == 'cgl') : null));

  const treeChartRef = ref();
  const treeOption = ref({});

  const getLabelColor = (actual?: any, target?: any) => {
    const a = Number(actual);
    const t = Number(target);
    return !isNaN(a) && !isNaN(t) && a < t ? '#ff4d4f' : '#fff';
  };

  const getTreeData = () => [
    {
      name: `总成材率: ${totalYieldAll.value?.totalznyield ?? '-'}% (目标: ${totalYieldAll.value?.targetvalue ?? '-'}%)`,
      label: { color: getLabelColor(totalYieldAll.value?.totalznyield, totalYieldAll.value?.targetvalue) },
      children: [
        {
          name: `冷轧成材率: ${coldYield.value?.totalznyield ?? '-'}% (目标: ${coldYield.value?.targetvalue ?? '-'}%)`,
          label: { color: getLabelColor(coldYield.value?.totalznyield, coldYield.value?.targetvalue) },
          children: [
            {
              name: `连退1630成材率: ${cal1630Yield.value?.totalznyield ?? '-'}% (目标: ${cal1630Yield.value?.targetvalue ?? '-'}%)`,
              label: { position: 'left', align: 'right', color: getLabelColor(cal1630Yield.value?.totalznyield, cal1630Yield.value?.targetvalue) },
            },
            {
              name: `连退2150成材率: ${cal2150Yield.value?.totalznyield ?? '-'}% (目标: ${cal2150Yield.value?.targetvalue ?? '-'}%)`,
              label: { position: 'right', align: 'left', color: getLabelColor(cal2150Yield.value?.totalznyield, cal2150Yield.value?.targetvalue) },
            },
          ],
        },
        {
          name: `镀锌成材率: ${cglYield.value?.totalznyield ?? '-'}% (目标: ${cglYield.value?.targetvalue ?? '-'}%)`,
          label: { color: getLabelColor(cglYield.value?.totalznyield, cglYield.value?.targetvalue) },
        },
      ],
    },
  ];

  const cal1630Yield = computed(() => (Array.isArray(totalYield.value) ? totalYield.value.find((item: any) => item.linename == 'cal1630') : null));
  const cal2150Yield = computed(() => (Array.isArray(totalYield.value) ? totalYield.value.find((item: any) => item.linename == 'cal2150') : null));

  const updateTreeOption = () => {
    treeOption.value = {
      tooltip: { trigger: 'item', triggerOn: 'mousemove' },
      series: [
        {
          type: 'tree',
          data: getTreeData(),
          top: '5%',
          left: '30%',
          bottom: '35%',
          right: '25%',
          symbolSize: 18,
          orient: 'TB', // 纵向 top-bottom
          nodePadding: 160, // 增大叶子节点间距
          label: {
            color: '#fff',
            position: 'left',
            verticalAlign: 'middle',
            align: 'right',
            fontSize: 16,
            // 移除阴影
            textShadowBlur: 0,
            textShadowColor: 'transparent',
            // 移除描边
            textBorderWidth: 0, // 关键：将描边宽度设为0
            textBorderColor: 'transparent', // 确保描边颜色透明
          },
          leaves: {
            label: {
              position: 'bottom',
              verticalAlign: 'top',
              align: 'left',
              fontSize: 15,
              distance: 10,
              // 移除阴影
              textShadowBlur: 0,
              textShadowColor: 'transparent',
              // 移除描边
              textBorderWidth: 0, // 关键：将描边宽度设为0
              textBorderColor: 'transparent',
            },
          },
          expandAndCollapse: false,
          animationDuration: 500,
          animationDurationUpdate: 500,
        },
      ],
    };

    // 更新图表
    nextTick(() => {
      if (treeChartRef.value) {
        const chart = echarts.getInstanceByDom(treeChartRef.value);
        if (chart) {
          chart.setOption(treeOption.value);

          // 添加点击事件监听
          chart.off('click'); // 先移除之前的监听器
          chart.on('click', handleTreeClick);
        }
      }
    });
  };

  watch([totalYieldAll, coldYield, cglYield], updateTreeOption, { immediate: true });

  const dateChange = async (cardType: string, val: string) => {
    let dbegin = '';
    let dend = '';

    // 获取当前日期
    const today = new Date();

    switch (val) {
      case 'day':
        // 今天
        const dayStart = new Date(today.getFullYear(), today.getMonth(), today.getDate());
        const dayEnd = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59);
        dbegin = `${dayStart.getFullYear()}-${String(dayStart.getMonth() + 1).padStart(2, '0')}-${String(dayStart.getDate()).padStart(
          2,
          '0'
        )} 00:00:01`;
        dend = `${dayEnd.getFullYear()}-${String(dayEnd.getMonth() + 1).padStart(2, '0')}-${String(dayEnd.getDate()).padStart(2, '0')} 23:59:59`;
        dateRange.value = [dayStart, dayEnd];
        break;
      case 'week':
        // 本周
        const weekStart = new Date(today.setDate(today.getDate() - today.getDay()));
        const weekEnd = new Date(today.setDate(today.getDate() - today.getDay() + 6));
        dbegin = `${weekStart.getFullYear()}-${String(weekStart.getMonth() + 1).padStart(2, '0')}-${String(weekStart.getDate()).padStart(
          2,
          '0'
        )} 00:00:01`;
        dend = `${weekEnd.getFullYear()}-${String(weekEnd.getMonth() + 1).padStart(2, '0')}-${String(weekEnd.getDate()).padStart(2, '0')} 23:59:59`;
        dateRange.value = [weekStart, weekEnd];
        break;
      case 'month':
        // 本月
        const monthStart = new Date(today.getFullYear(), today.getMonth(), 1);
        const monthEnd = new Date(today.getFullYear(), today.getMonth() + 1, 0);
        dbegin = `${monthStart.getFullYear()}-${String(monthStart.getMonth() + 1).padStart(2, '0')}-${String(monthStart.getDate()).padStart(
          2,
          '0'
        )} 00:00:01`;
        dend = `${monthEnd.getFullYear()}-${String(monthEnd.getMonth() + 1).padStart(2, '0')}-${String(monthEnd.getDate()).padStart(
          2,
          '0'
        )} 23:59:59`;
        dateRange.value = [monthStart, monthEnd];
        break;
    }

    // 调用接口获取数据
    await fetchAllProcessIndexDetails(dbegin, dend);
    await fetchAllProcessIndexReason(dbegin, dend);

    await fetchAllProcessProductReason(dbegin, dend);
    await fetchAllProcessMachinedetails(dbegin, dend);

    // 质量缺陷
    if (activeReasonTab.value == 'qualityDefect') {
      fetchQualityDefectTableData();
    }
  };

  // 监听日期范围变化
  const handleDateRangeChange = async (val: [Date, Date] | null) => {
    if (val) {
      const [start, end] = val;
      const dbegin = `${start.getFullYear()}-${String(start.getMonth() + 1).padStart(2, '0')}-${String(start.getDate()).padStart(2, '0')} 00:00:01`;
      const dend = `${end.getFullYear()}-${String(end.getMonth() + 1).padStart(2, '0')}-${String(end.getDate()).padStart(2, '0')} 23:59:59`;
      await fetchAllProcessIndexDetails(dbegin, dend);
      await fetchAllProcessIndexReason(dbegin, dend);
      await fetchAllProcessProductReason(dbegin, dend);
      await fetchAllProcessMachinedetails(dbegin, dend);
      // 质量缺陷
      if (activeReasonTab.value == 'qualityDefect') {
        fetchQualityDefectTableData();
      }
    }
  };

  const fetchAllProcessIndexReason = async (dbegin: string, dend: string, pageIndex?: number, pageSize?: number) => {
    try {
      const params: any = { dbegin, dend, linename: searchParams.prodLine };
      if (pageIndex !== undefined) params.pageIndex = pageIndex;
      if (pageSize !== undefined) params.pageSize = pageSize;
      const res = await ActualPerformanceRollDeviationApi.get_allprocessindexReason(params);

      if (res.data && res.data.data) {
        const data = res.data.data;

        // 未完成原因 - Safely access the reason
        unCompleteReason.value = data.unCompleteReason?.[0]?.uncompletereason ?? '';
        reasonTableData.value = data.otherReason;
        reasonGraphData.value = data.otherReason
          .map((item: any) => ({
            name: item.uncompletereason,
            value: Number(item.rate) || 0,
          }))
          .filter((item: any) => item.value > 0);

        // 假设接口返回总条数字段为res.data.total
        if (res.data.count !== undefined) {
          totalCount.value = res.data.count;
          reasonTotalCount.value = res.data.count; // 同时更新异常原因的总数
        }

        // 修复初次加载不渲染问题，强制触发resize
        nextTick(() => {
          window.dispatchEvent(new Event('resize'));
        });
      } else {
        // Clear all data if response structure is not as expected
        unCompleteReason.value = '';
        reasonTableData.value = [];
        reasonGraphData.value = [];
        totalCount.value = 0;
        reasonTotalCount.value = 0;
        ElMessage.info(res.data?.msg || '未查询到数据或响应格式不正确');
      }
    } catch (error) {
      ElMessage.error('获取数据失败');
      // Also clear data on error to avoid displaying stale information
      unCompleteReason.value = '';
      reasonTableData.value = [];
      reasonGraphData.value = [];
      totalCount.value = 0;
      reasonTotalCount.value = 0;
    }
  };

  // 异常原因分页数据获取
  const fetchReasonPagedData = async () => {
    if (dateRange.value && dateRange.value.length === 2) {
      const [start, end] = dateRange.value;
      const dbegin = `${start.getFullYear()}-${String(start.getMonth() + 1).padStart(2, '0')}-${String(start.getDate()).padStart(2, '0')} 00:00:01`;
      const dend = `${end.getFullYear()}-${String(end.getMonth() + 1).padStart(2, '0')}-${String(end.getDate()).padStart(2, '0')} 23:59:59`;
      await fetchAllProcessIndexReason(dbegin, dend, reasonCurrentPage.value, reasonPageSize.value);
    }
  };

  // 机组计算成材率分页数据获取
  const fetchTeamPagedData = async () => {
    if (dateRange.value && dateRange.value.length === 2) {
      const [start, end] = dateRange.value;
      const dbegin = `${start.getFullYear()}-${String(start.getMonth() + 1).padStart(2, '0')}-${String(start.getDate()).padStart(2, '0')} 00:00:01`;
      const dend = `${end.getFullYear()}-${String(end.getMonth() + 1).padStart(2, '0')}-${String(end.getDate()).padStart(2, '0')} 23:59:59`;
      await fetchAllProcessMachinedetails(dbegin, dend, teamCurrentPage.value, teamPageSize.value);
    }
  };

  // 产品品类分页数据获取
  const fetchSteelGradePagedData = async () => {
    if (dateRange.value && dateRange.value.length === 2) {
      const [start, end] = dateRange.value;
      const dbegin = `${start.getFullYear()}-${String(start.getMonth() + 1).padStart(2, '0')}-${String(start.getDate()).padStart(2, '0')} 00:00:01`;
      const dend = `${end.getFullYear()}-${String(end.getMonth() + 1).padStart(2, '0')}-${String(end.getDate()).padStart(2, '0')} 23:59:59`;
      await fetchAllProcessProductDetail(dbegin, dend, steelGradeCurrentPage.value, steelGradePageSize.value);
    }
  };

  const fetchAllProcessProductDetail = async (dbegin: string, dend: string, pageIndex?: number, pageSize?: number) => {
    try {
      const params: any = { dbegin, dend, linename: searchParams.prodLine };
      if (pageIndex !== undefined) params.pageIndex = pageIndex;
      if (pageSize !== undefined) params.pageSize = pageSize;
      const res = await ActualPerformanceRollDeviationApi.get_allprocessproductDetail(params);

      if (res.data && res.data.data) {
        const data = res.data.data;

        // 产品品类
        const productTypeData = data.productType ?? [];
        steelGradeTableData.value = productTypeData;
        steelGradeGraphData.value = productTypeData
          .map((item: any) => ({
            name: item.producttype,
            value: Number(item.rate * 100).toFixed(2) || 0,
          }))
          .filter((item: any) => item.value > 0);

        // 假设接口返回总条数字段为res.data.total
        if (res.data.count !== undefined) {
          steelGradeTotalCount.value = res.data.count;
        }

        // 修复初次加载不渲染问题，强制触发resize
        nextTick(() => {
          window.dispatchEvent(new Event('resize'));
        });
      } else {
        // Clear all data if response structure is not as expected
        steelGradeTableData.value = [];
        steelGradeGraphData.value = [];
        steelGradeTotalCount.value = 0;
        ElMessage.info(res.data?.msg || '未查询到数据或响应格式不正确');
      }
    } catch (error) {
      ElMessage.error('获取数据失败');
      // Also clear data on error to avoid displaying stale information
      steelGradeTableData.value = [];
      steelGradeGraphData.value = [];
      steelGradeTotalCount.value = 0;
    }
  };

  const fetchProductReasonPagedData = async () => {
    if (dateRange.value && dateRange.value.length === 2) {
      const [start, end] = dateRange.value;
      const dbegin = `${start.getFullYear()}-${String(start.getMonth() + 1).padStart(2, '0')}-${String(start.getDate()).padStart(2, '0')} 00:00:01`;
      const dend = `${end.getFullYear()}-${String(end.getMonth() + 1).padStart(2, '0')}-${String(end.getDate()).padStart(2, '0')} 23:59:59`;
      await fetchAllProcessProductReason(dbegin, dend, steelGradeCurrentPage.value, steelGradePageSize.value);
    }
  };

  const fetchAllProcessProductReason = async (dbegin: string, dend: string, pageIndex?: number, pageSize?: number) => {
    try {
      const params: any = { dbegin, dend, linename: searchParams.prodLine };
      if (pageIndex !== undefined) params.pageIndex = pageIndex;
      if (pageSize !== undefined) params.pageSize = pageSize;
      const res = await ActualPerformanceRollDeviationApi.get_allprocessproductReason(params);

      if (res.data && res.data.data) {
        const data = res.data.data;

        // 产品品类
        const productTypeData = data ?? [];
        productTableData.value = productTypeData;
        productReasonGraphData.value = productTypeData
          .map((item: any) => ({
            name: item.producttype,
            value: Number(item.rate) || 0,
          }))
          .filter((item: any) => item.value > 0);

        // 假设接口返回总条数字段为res.data.total
        if (res.data.count !== undefined) {
          productReasonTotalCount.value = res.data.count;
        }

        // 修复初次加载不渲染问题，强制触发resize
        nextTick(() => {
          window.dispatchEvent(new Event('resize'));
        });
      } else {
        // Clear all data if response structure is not as expected
        productTableData.value = [];
        productReasonGraphData.value = [];
        productReasonTotalCount.value = 0;
        ElMessage.info(res.data?.msg || '未查询到数据或响应格式不正确');
      }
    } catch (error) {
      ElMessage.error('获取数据失败');
      // Also clear data on error to avoid displaying stale information
      productTableData.value = [];
      productReasonGraphData.value = [];
      productReasonTotalCount.value = 0;
    }
  };

  const fetchAllProcessMachinedetails = async (dbegin: string, dend: string, pageIndex?: number, pageSize?: number) => {
    try {
      const params: any = { dbegin, dend, linename: 'all' };
      if (pageIndex !== undefined) params.pageIndex = pageIndex;
      if (pageSize !== undefined) params.pageSize = pageSize;
      const res = await ActualPerformanceRollDeviationApi.get_allprocessmachinedetails(params);

      if (res.data && res.data.data) {
        const data = res.data.data;

        // 机组计算成材率
        const unitCalculationYieldData = data.unitCalculationYield ?? [];
        teamTableData.value = unitCalculationYieldData;
        teamGraphData.value = unitCalculationYieldData
          .map((item: any) => ({
            name: item.linename,
            value: Number(item.rate) || 0,
          }))
          .filter((item: any) => item.value > 0);

        // 假设接口返回总条数字段为res.data.total
        if (res.data.count !== undefined) {
          teamTotalCount.value = res.data.count; // 同时更新异常原因的总数
        }

        // 修复初次加载不渲染问题，强制触发resize
        nextTick(() => {
          window.dispatchEvent(new Event('resize'));
        });
      } else {
        // Clear all data if response structure is not as expected
        teamTableData.value = [];
        teamGraphData.value = [];
        teamTotalCount.value = 0;
        ElMessage.info(res.data?.msg || '未查询到数据或响应格式不正确');
      }
    } catch (error) {
      ElMessage.error('获取数据失败');
      // Also clear data on error to avoid displaying stale information
      teamTableData.value = [];
      teamGraphData.value = [];
      teamTotalCount.value = 0;
    }
  };

  const fetchAllProcessIndexDetails = async (dbegin: string, dend: string, pageIndex?: number, pageSize?: number) => {
    try {
      const params: any = { dbegin, dend, linename: 'all' };
      if (pageIndex !== undefined) params.pageIndex = pageIndex;
      if (pageSize !== undefined) params.pageSize = pageSize;
      const res = await ActualPerformanceRollDeviationApi.get_allprocessindexdetails(params);

      if (res.data && res.data.data) {
        const data = res.data.data;

        // 总成材率
        totalYield.value = data.totalYield ?? [];

        // 假设接口返回总条数字段为res.data.total
        if (res.data.count !== undefined) {
          totalCount.value = res.data.count;
        }

        // 新增全流程成材率损失分析
        getLossAnalysis('all', totalYieldAll.value.totalznyield, totalYieldAll.value.targetvalue);

        // 修复初次加载不渲染问题，强制触发resize
        nextTick(() => {
          window.dispatchEvent(new Event('resize'));
        });
      } else {
        // Clear all data if response structure is not as expected
        totalYield.value = [];
        totalCount.value = 0;
        ElMessage.info(res.data?.msg || '未查询到数据或响应格式不正确');
      }
    } catch (error) {
      ElMessage.error('获取数据失败');
      // Also clear data on error to avoid displaying stale information
      totalYield.value = [];
      totalCount.value = 0;
    }
  };

  const fetchPagedData = async () => {
    await fetchAllProcessIndexDetailsWithPage();
  };

  const handleSizeChange = (val: number) => {
    pageSize.value = val;
    currentPage.value = 1;
    fetchPagedData();
  };

  const handleCurrentChange = (val: number) => {
    currentPage.value = val;
    fetchPagedData();
  };

  // 异常原因分页处理函数
  const handleReasonSizeChange = (val: number) => {
    reasonPageSize.value = val;
    reasonCurrentPage.value = 1;
    fetchReasonPagedData();
  };

  const handleReasonCurrentChange = (val: number) => {
    reasonCurrentPage.value = val;
    fetchReasonPagedData();
  };

  // 机组计算成材率分页处理函数
  const handleTeamSizeChange = (val: number) => {
    teamPageSize.value = val;
    teamCurrentPage.value = 1;
    fetchTeamPagedData();
  };

  const handleTeamCurrentChange = (val: number) => {
    teamCurrentPage.value = val;
    fetchTeamPagedData();
  };

  // 产品品类分页处理函数
  const handleSteelGradeSizeChange = (val: number) => {
    steelGradePageSize.value = val;
    steelGradeCurrentPage.value = 1;
    fetchSteelGradePagedData();
  };

  const handleSteelGradeCurrentChange = (val: number) => {
    steelGradeCurrentPage.value = val;
    fetchSteelGradePagedData();
  };

  const handleProductReasonSizeChange = (val: number) => {
    steelGradePageSize.value = val;
    steelGradeCurrentPage.value = 1;
    fetchProductReasonPagedData();
  };

  const handleProductReasonCurrentChange = (val: number) => {
    steelGradeCurrentPage.value = val;
    fetchProductReasonPagedData();
  };

  const activeReasonTab = ref<'reason' | 'productReason' | 'qualityDefect'>('reason');

  // 异常原因行点击处理
  function handleReasonRowClick(row: any) {
    console.log('异常原因表格点击行数据:', row);

    // 产线映射 - 根据当前选择的产线
    const prodLineMap: Record<string, string> = {
      tcm2280: 'tcm2280',
      cal1630: 'cal1630',
      cal2150: 'cal2150',
      cgl1870: 'cgl1870',
      rcl1630: 'rcl1630',
      rcl2150: 'rcl2150',
      rcl1870: 'rcl1870',
    };

    const tabName = prodLineMap[searchParams.prodLine] || 'tcm2280';

    router.push({
      path: '/yiledAndSubsection/CalculationOfYieldRate',
      query: {
        tab: tabName,
        yieldRemark: row.uncompletereason, // 传递异常原因
        start: dateRange.value?.[0] ? dateRange.value[0].toISOString() : '',
        end: dateRange.value?.[1] ? dateRange.value[1].toISOString() : '',
      },
    });
  }

  function handleProductReasonRowClick(row: any) {
    console.log('产品品类异常原因表格点击行数据:', row);

    // 产线映射 - 根据当前选择的产线
    const prodLineMap: Record<string, string> = {
      tcm2280: 'tcm2280',
      cal1630: 'cal1630',
      cal2150: 'cal2150',
      cgl1870: 'cgl1870',
      rcl1630: 'rcl1630',
      rcl2150: 'rcl2150',
      rcl1870: 'rcl1870',
    };

    const tabName = prodLineMap[searchParams.prodLine] || 'tcm2280';

    router.push({
      path: '/yiledAndSubsection/CalculationOfYieldRate',
      query: {
        tab: tabName,
        yieldRemark: row.uncompletereason, // 传递异常原因或产品品类
        steelGrade: row.producttype,
        start: dateRange.value?.[0] ? dateRange.value[0].toISOString() : '',
        end: dateRange.value?.[1] ? dateRange.value[1].toISOString() : '',
      },
    });
  }

  function openDetail(row: any) {
    // 产线映射 - 根据当前选择的产线
    const prodLineMap: Record<string, string> = {
      tcm2280: 'tcm2280',
      cal1630: 'cal1630',
      cal2150: 'cal2150',
      cgl1870: 'cgl1870',
      rcl1630: 'rcl1630',
      rcl2150: 'rcl2150',
      rcl1870: 'rcl1870',
    };

    router.push({
      path: '/yiledAndSubsection/qualityDefect',
      query: {
        linename: searchParams.prodLine, // 传递异常原因或产品品类
        defectclass: row.defectclass,
        start: dateRange.value?.[0] ? dateRange.value[0].toISOString() : '',
        end: dateRange.value?.[1] ? dateRange.value[1].toISOString() : '',
      },
    });
  }

  const currentReasonPieData = computed(() =>
    activeReasonTab.value === 'reason'
      ? reasonGraphData.value
      : activeReasonTab.value === 'qualityDefect'
      ? qualityDefectGraphData.value
      : productReasonGraphData.value
  );

  const fetchAllProcessIndexDetailsWithPage = async () => {
    if (dateRange.value && dateRange.value.length === 2) {
      const [start, end] = dateRange.value;
      const dbegin = `${start.getFullYear()}-${String(start.getMonth() + 1).padStart(2, '0')}-${String(start.getDate()).padStart(2, '0')} 00:00:01`;
      const dend = `${end.getFullYear()}-${String(end.getMonth() + 1).padStart(2, '0')}-${String(end.getDate()).padStart(2, '0')} 23:59:59`;
      //await fetchAllProcessIndexDetails(dbegin, dend, currentPage.value, pageSize.value);
      await fetchAllProcessIndexReason(dbegin, dend, reasonCurrentPage.value, reasonPageSize.value);
      await fetchAllProcessProductDetail(dbegin, dend, steelGradeCurrentPage.value, steelGradePageSize.value);
      await fetchAllProcessProductReason(dbegin, dend, productReasonCurrentPage.value, productReasonPageSize.value);
      //await fetchAllProcessMachinedetails(dbegin, dend,teamCurrentPage.value, teamPageSize.value);

      // 质量缺陷
      if (activeReasonTab.value == 'qualityDefect') {
        fetchQualityDefectTableData();
      }
    }
  };

  function handleTeamRowMouseEnter(row: any) {
    hoverTeamRow.value = row;
  }

  function handleTeamRowMouseLeave() {
    hoverTeamRow.value = null;
  }

  function teamRowClassName({ row }: { row: any }) {
    return hoverTeamRow.value === row ? 'team-row-hover' : '';
  }

  function handleTeamRowClick(row: any) {
    console.log('机组计算成材率表格点击行数据:', row);
    // tabMap 映射，兼容中英文
    const tabMap: Record<string, string> = {
      镀锌1870: 'cal1870',
      连退1630: 'cal1630',
      连退2150: 'cgl2150',
      酸轧2280: 'tcm2280',
      cal1870: 'cal1870',
      cal1630: 'cal1630',
      cgl2150: 'cgl2150',
      tcm2280: 'tcm2280',
    };
    const tabName = tabMap[row.linename?.trim()] || 'cal1870';
    router.push({
      path: '/yiledAndSubsection/CalculationOfYieldRate',
      query: {
        tab: tabName,
        start: dateRange.value?.[0] ? dateRange.value[0].toISOString() : '',
        end: dateRange.value?.[1] ? dateRange.value[1].toISOString() : '',
      },
    });
  }

  function handleProductTypeRowClick(row: any) {
    console.log('机组计算成材率表格点击行数据:', row);
    // tabMap 映射，兼容中英文
    const tabMap: Record<string, string> = {
      镀锌1870: 'cal1870',
      连退1630: 'cal1630',
      连退2150: 'cgl2150',
      酸轧2280: 'tcm2280',
      cal1870: 'cal1870',
      cal1630: 'cal1630',
      cgl2150: 'cgl2150',
      tcm2280: 'tcm2280',
    };
    const tabName = tabMap[row.linename?.trim()] || 'cal1870';
    router.push({
      path: '/yiledAndSubsection/CalculationOfYieldRate',
      query: {
        tab: tabName,
        steelGrade: row.producttype,
        start: dateRange.value?.[0] ? dateRange.value[0].toISOString() : '',
        end: dateRange.value?.[1] ? dateRange.value[1].toISOString() : '',
      },
    });
  }

  function handlePieClick(pieData: any) {
    const tabMap: Record<string, string> = {
      cgl1870: 'cal1870',
      cal2150: 'cgl2150',
      cal1630: 'cal1630',
      tcm2280: 'tcm2280',
    };
    const tabName = tabMap[(pieData.name as string)?.trim()] || 'cal1870';
    router.push({
      path: '/yiledAndSubsection/CalculationOfYieldRate',
      query: {
        tab: tabName,
        start: dateRange.value?.[0] ? dateRange.value[0].toISOString() : '',
        end: dateRange.value?.[1] ? dateRange.value[1].toISOString() : '',
      },
    });
  }

  // 树状图点击处理函数
  function handleTreeClick(params: any) {
    // 定义配置映射表：dataIndex 对应的数据参数
    const configs = [
      {
        dataIndex: 1,
        linename: 'all',
        data: totalYieldAll.value,
      },
      {
        dataIndex: 2,
        linename: 'cal',
        data: coldYield.value,
      },
      {
        dataIndex: 3,
        linename: 'cal1630',
        data: cal1630Yield.value,
      },
      {
        dataIndex: 4,
        linename: 'cal2150',
        data: cal2150Yield.value,
      },
      {
        dataIndex: 5,
        linename: 'cgl',
        data: cglYield.value,
      },
    ];

    // 查找当前 dataIndex 对应的配置
    const currentConfig = configs.find((item) => item.dataIndex === params.dataIndex);

    if (currentConfig) {
      const { linename, data } = currentConfig;
      const actual = data.totalznyield;
      const target = data.targetvalue;
      getLossAnalysis(linename, actual, target);
    }
    // calculateSpan(0);
    // calculateSpan(1);
    // // 根据点击的节点名称判断跳转到哪个产线
    // const nodeName = params.name || '';
    // let tabName = '';
    // if (nodeName.includes('总成材率')) {
    //   // 总成材率点击，跳转到当前选择的产线
    //   const prodLineMap: Record<string, string> = {
    //     tcm2280: 'tcm2280',
    //     cal1630: 'cal1630',
    //     cal2150: 'cal2150',
    //     cgl1870: 'cgl1870',
    //     rcl1630: 'rcl1630',
    //     rcl2150: 'rcl2150',
    //     rcl1870: 'rcl1870',
    //   };
    //   tabName = prodLineMap[searchParams.prodLine] || 'tcm2280';
    // } else if (nodeName.includes('冷轧成材率')) {
    //   // 冷轧成材率点击，跳转到当前选择的产线
    //   const prodLineMap: Record<string, string> = {
    //     tcm2280: 'tcm2280',
    //     cal1630: 'cal1630',
    //     cal2150: 'cal2150',
    //     cgl1870: 'cgl1870',
    //     rcl1630: 'rcl1630',
    //     rcl2150: 'rcl2150',
    //     rcl1870: 'rcl1870',
    //   };
    //   tabName = prodLineMap[searchParams.prodLine] || 'tcm2280';
    // } else if (nodeName.includes('连退1630')) {
    //   tabName = 'cal1630';
    // } else if (nodeName.includes('连退2150')) {
    //   tabName = 'cal2150';
    // } else if (nodeName.includes('镀锌成材率')) {
    //   tabName = 'cgl1870';
    // } else {
    //   // 默认跳转到当前选择的产线
    //   const prodLineMap: Record<string, string> = {
    //     tcm2280: 'tcm2280',
    //     cal1630: 'cal1630',
    //     cal2150: 'cal2150',
    //     cgl1870: 'cgl1870',
    //     rcl1630: 'rcl1630',
    //     rcl2150: 'rcl2150',
    //     rcl1870: 'rcl1870',
    //   };
    //   tabName = prodLineMap[searchParams.prodLine] || 'tcm2280';
    // }
    // router.push({
    //   path: '/yiledAndSubsection/CalculationOfYieldRate',
    //   query: {
    //     tab: tabName,
    //     start: dateRange.value?.[0] ? dateRange.value[0].toISOString() : '',
    //     end: dateRange.value?.[1] ? dateRange.value[1].toISOString() : '',
    //   },
    // });
  }

  function onProdLineChange() {
    currentPage.value = 1;
    reasonCurrentPage.value = 1; // 重置异常原因分页
    teamCurrentPage.value = 1; // 重置机组计算成材率分页
    steelGradeCurrentPage.value = 1; // 重置产品品类分页
    fetchPagedData();
  }

  onBeforeMount(() => {
    useUserStore().setTagNav(data.value);
  });
  onMounted(() => {
    // 默认加载当天数据
    const today = new Date();
    const dayStart = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 6);
    const dayEnd = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59);
    dateRange.value = [dayStart, dayEnd];

    const dbegin = `${dayStart.getFullYear()}-${String(dayStart.getMonth() + 1).padStart(2, '0')}-${String(dayStart.getDate()).padStart(
      2,
      '0'
    )} 00:00:01`;
    const dend = `${dayEnd.getFullYear()}-${String(dayEnd.getMonth() + 1).padStart(2, '0')}-${String(dayEnd.getDate()).padStart(2, '0')} 23:59:59`;
    fetchAllProcessIndexDetails(dbegin, dend, currentPage.value, pageSize.value);

    fetchAllProcessIndexReason(dbegin, dend, reasonCurrentPage.value, reasonPageSize.value);

    fetchAllProcessProductDetail(dbegin, dend, steelGradeCurrentPage.value, steelGradePageSize.value);

    fetchAllProcessProductReason(dbegin, dend, productReasonCurrentPage.value, productReasonPageSize.value);

    fetchAllProcessMachinedetails(dbegin, dend, teamCurrentPage.value, teamPageSize.value);

    // 初始化树状图
    nextTick(() => {
      if (treeChartRef.value) {
        const chart = echarts.init(treeChartRef.value);
        chart.setOption(treeOption.value);

        // 监听窗口大小变化
        window.addEventListener('resize', () => {
          chart.resize();
        });
      }
    });
  });

  // 质量缺陷相关
  const qualityDefectTableData = ref<any[]>([]);
  const qualityDefectGraphData = ref<any[]>([]);
  const qualityDefectCurrentPage = ref(1);
  const qualityDefectPageSize = ref(5);
  const qualityDefectTotalCount = ref(0);

  const handleReasonTabClick = (tab: TabsPaneContext, event: Event) => {
    const name = String(tab.paneName ?? '');
    if (name == 'qualityDefect') {
      fetchQualityDefectTableData();
    }
  };

  const fetchQualityDefectTableData = async () => {
    const params: any = { linename: searchParams.prodLine, pageIndex: qualityDefectCurrentPage.value, pageSize: qualityDefectPageSize.value };
    if (dateRange.value && dateRange.value.length === 2) {
      const [start, end] = dateRange.value;
      const dbegin = `${start.getFullYear()}-${String(start.getMonth() + 1).padStart(2, '0')}-${String(start.getDate()).padStart(2, '0')} 00:00:01`;
      const dend = `${end.getFullYear()}-${String(end.getMonth() + 1).padStart(2, '0')}-${String(end.getDate()).padStart(2, '0')} 23:59:59`;
      params.dbegin = dbegin;
      params.dend = dend;
    } else {
      params.dbegin = '';
      params.dend = '';
    }
    try {
      const res = await ActualPerformanceRollDeviationApi.getQualityDefect(params);
      if (res.data && res.data.data) {
        const data = res.data.data;
        const qualityDefectData = data ?? [];
        qualityDefectTableData.value = qualityDefectData;
        const totallossWeight = qualityDefectData.reduce((acc: any, cur: any) => acc + cur.lostweight, 0);
        qualityDefectGraphData.value = qualityDefectData
          .map((item: any) => ({
            name: item.defectclass,
            value: ((Number(item.lostweight) / Number(totallossWeight)) * 100).toFixed(2) || 0,
          }))
          .filter((item: any) => item.value > 0);

        // 假设接口返回总条数字段为res.data.total
        if (res.data.count !== undefined) {
          qualityDefectTotalCount.value = res.data.count;
        }

        // 修复初次加载不渲染问题，强制触发resize
        nextTick(() => {
          window.dispatchEvent(new Event('resize'));
        });
      } else {
        productTableData.value = [];
        productReasonGraphData.value = [];
        productReasonTotalCount.value = 0;
        ElMessage.info(res.data?.msg || '未查询到数据或响应格式不正确');
      }
    } catch (error) {
      ElMessage.error('获取数据失败');
      qualityDefectTableData.value = [];
      qualityDefectGraphData.value = [];
      qualityDefectTotalCount.value = 0;
    }
  };

  const handleQualityDefectSizeChange = (val: number) => {
    qualityDefectPageSize.value = val;
    qualityDefectCurrentPage.value = 1;
    fetchQualityDefectTableData();
  };

  const handleQualityDefectCurrentChange = (val: number) => {
    qualityDefectCurrentPage.value = val;
    fetchQualityDefectTableData();
  };

  // ------------------------------------------------- 10.28修改 新增全流程成材率损失分析-----------------------------------------------------

  const lossAnalysisTableData = ref<any[]>([]);
  const title = ref('');

  const getSpanMap = (data: any) => {
    const processMap = new Map(); // 工序的合并信息
    const lineMap = new Map(); // 产线的合并信息

    data.forEach((item: any, index: any) => {
      // 构造层级唯一键
      const processKey = item.process;
      const lineKey = `${processKey}_${item.line}`;

      // 统计品名的合并行数
      if (!processMap.has(processKey)) {
        processMap.set(processKey, { start: index, count: 1 });
      } else {
        processMap.get(processKey).count++;
      }

      // 统计表面等级的合并行数
      if (!lineMap.has(lineKey)) {
        lineMap.set(lineKey, { start: index, count: 1 });
      } else {
        lineMap.get(lineKey).count++;
      }
    });

    return { processMap, lineMap };
  };

  const spanMap = ref(getSpanMap(lossAnalysisTableData.value));

  // TODO ERROR
  const spanFunc = ({ row, rowIndex, columnIndex }: { row: any; rowIndex: number; columnIndex: number }) => {
    const { processMap, lineMap } = spanMap.value;

    // 工序（第1列）
    if (columnIndex === 0) {
      const processKey = row.process;
      const process = processMap.get(processKey);
      if (process && rowIndex === process.start) {
        return { rowspan: process.count, colspan: 1 };
      } else {
        return { rowspan: 0, colspan: 0 };
      }
    }

    // 产线（第2列）
    if (columnIndex === 1) {
      const processKey = row.process;
      const lineKey = `${processKey}_${row.line}`;
      const line = lineMap.get(lineKey);
      if (line && rowIndex === line.start) {
        return { rowspan: line.count, colspan: 1 };
      } else {
        return { rowspan: 0, colspan: 0 };
      }
    }

    return { rowspan: 1, colspan: 1 };
  };

  const formatterDate = () => {
    if (dateRange.value && dateRange.value.length === 2) {
      const [start, end] = dateRange.value;
      const dbegin = `${start.getFullYear()}-${String(start.getMonth() + 1).padStart(2, '0')}-${String(start.getDate()).padStart(2, '0')} 00:00:01`;
      const dend = `${end.getFullYear()}-${String(end.getMonth() + 1).padStart(2, '0')}-${String(end.getDate()).padStart(2, '0')} 23:59:59`;
      return { dbegin, dend };
    }
    return { dbegin: '', dend: '' };
  };

  const getLossAnalysis = async (linename: string, totalznyield: string, targetvalue: string) => {
    try {
      const { dbegin, dend } = formatterDate();
      const params: any = {
        pageIndex: 1,
        pageSize: 20,
        dbegin: dbegin,
        dend: dend,
        linename: linename,
        totalznyield: totalznyield,
        targetvalue: targetvalue,
      };
      const res = await ActualPerformanceRollDeviationApi.getLossAnalysis(params);
      if (res.data && res.data.data) {
        lossAnalysisTableData.value = res.data.data.list_tbAllpricessIndexTableDto;
        title.value = res.data.data.details;
        if (lossAnalysisTableData.value.length > 0) spanMap.value = getSpanMap(lossAnalysisTableData.value);
      }
    } catch (error) {
      ElMessage.error('获取全流程成材率损失分析数据失败');
      lossAnalysisTableData.value = [];
    }
  };
</script>
<style lang="less" scoped>
  @border-radius: 8px;
  @primary-color: #2c69e8;
  @box-shadow: 0 2px 4px rgba(51, 102, 153, 0.5);

  .home {
    height: 105vh;
    overflow: hidden !important;
  }

  .top {
    width: 98%;
    height: 18vh;
    margin: 0.5% auto;
    color: #fff;
    font-size: 1.2rem;
    display: flex;

    .msg-title {
      margin-top: -7vh;
      margin-left: -0.7%;
      background-image: -webkit-linear-gradient(left, #0072ff, #00eaff, #01aaff);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      font-size: 2vh;
      font-weight: bolder;
    }

    .information {
      margin-left: -5.5vw;
      margin-top: -4vh;
      color: #fff;
      width: 100%;
      height: 10vh;
      border: 2px solid #3981d9;
      border-radius: 5px;
      padding: 0 0.2vw;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .left-content {
        flex: 1;
        text-align: left;
        padding-left: 1vw;
      }

      .right-content {
        flex: 0 0 auto;
        padding-right: 1vw;
      }
    }
  }

  .main-container {
    width: 98%;
    height: 80%;
    flex-wrap: wrap;
    overflow: hidden;
    margin-top: -0.5vh;
  }

  .main-container .card-container {
    // margin-top: 2vh;
    width: 49.5%;
    border-radius: @border-radius;
    height: 38vh;
    background-color: transparent !important;
    box-shadow: @box-shadow;
    transition: box-shadow 0.3s ease;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 2vw;
    position: relative;
    z-index: 1;
    flex-direction: row;

    .card-header {
      color: #fff;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .card-title {
        background-image: -webkit-linear-gradient(left, #0072ff, #00eaff, #01aaff);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        font-size: 2vh;
        font-weight: bolder;
      }

      .card-title1 {
        background-image: -webkit-linear-gradient(left, #0072ff, #00eaff, #01aaff);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        font-size: 5vh;
        font-weight: bolder;
      }
    }

    :deep(.el-select) {
      width: 1rem;
      right: 1rem;
      background-color: transparent !important;
      color: #fff;
    }

    :deep(.el-select__wrapper) {
      background-color: transparent !important;
    }

    :deep(.el-input__wrapper) {
      background-color: #223671 !important;
      box-shadow: none !important;
    }

    :deep(.el-input__inner) {
      color: #fff !important;
    }

    :deep(.el-select-dropdown__item) {
      color: #fff !important;
    }

    :deep(.el-select-dropdown__item.hover, .el-select-dropdown__item:hover) {
      background-color: #2f59af !important;
    }

    :deep(.el-select-dropdown) {
      background-color: #223671 !important;
      border: 1px solid #2f59af !important;
    }

    :deep(.el-date-picker) {
      background-color: #223671 !important;
      border: 1px solid #2f59af !important;
      color: #fff !important;
    }

    :deep(.el-date-picker__header) {
      color: #fff !important;
    }

    :deep(.el-date-picker__header-label) {
      color: #fff !important;
    }

    :deep(.el-date-table th) {
      color: #fff !important;
    }

    :deep(.el-date-table td) {
      color: #fff !important;
    }

    :deep(.el-date-table td.available:hover) {
      color: #fff !important;
      background-color: #2f59af !important;
    }

    :deep(.el-date-table td.current:not(.disabled) span) {
      background-color: #2f59af !important;
      color: #fff !important;
    }

    :deep(.el-date-picker__time-header) {
      color: #fff !important;
    }

    :deep(.el-time-panel) {
      background-color: #223671 !important;
      border: 1px solid #2f59af !important;
    }

    :deep(.el-time-panel__content) {
      color: #fff !important;
    }

    :deep(.el-time-spinner__item) {
      color: #fff !important;
    }

    :deep(.el-time-spinner__item.active:not(.disabled)) {
      color: #fff !important;
      background-color: #2f59af !important;
    }

    :deep(.el-time-spinner__item:hover:not(.disabled):not(.active)) {
      background-color: #2f59af !important;
    }

    :deep(.el-date-editor .el-range-separator) {
      color: #fff !important;
    }

    :deep(.el-date-editor .el-range-input) {
      color: #fff !important;
    }

    :deep(.el-date-editor .el-range__icon) {
      color: #fff !important;
    }

    :deep(.el-date-editor .el-range__close-icon) {
      color: #fff !important;
    }

    :deep(.el-date-editor.el-input) {
      width: 300px !important;
    }

    :deep(.el-card) {
      width: 100%;
      height: 100%;
      background-color: transparent !important;
      border-radius: @border-radius;
      border: #0072ff solid 2px;
    }

    .card-body {
      display: flex;
      flex-direction: row;
      flex-wrap: nowrap;
      justify-content: space-between;
      // max-height: 25vh;
      // max-width: 45vw;
      // position: absolute;

      .graph-container {
        height: 20vh;
        width: 30vw;
        display: flex;
        justify-content: center;
        color: #fff;

        .table-item {
          color: #fff;
          width: 100%;
          height: 100%;
          display: flex;
          justify-content: space-around;
          flex-direction: column;
          align-items: center;
        }
      }

      .table-container {
        width: 26vw;
        //display: flex;
        //justify-content: center;

        :deep(.el-table) {
          height: 200px;
          overflow: hidden;
          overflow-y: auto;
          width: 100%;
          z-index: 1;
          --el-table-row-hover-bg-color: unset;
          --el-table-border-color: transparent;
        }

        .table-item {
          color: #fff;
          width: 100%;
          height: 100%;
        }
      }

      .q-table-container {
        width: 30vw;
        //display: flex;
        //justify-content: center;

        :deep(.el-table) {
          height: 200px;
          overflow: hidden;
          overflow-y: auto;
          width: 100%;
          z-index: 1;
          --el-table-row-hover-bg-color: unset;
          --el-table-border-color: transparent;
        }

        .table-item {
          color: #fff;
          width: 100%;
          height: 100%;
        }
      }
    }
  }

  .card-container:hover {
    box-shadow: 0 8px 16px rgba(51, 102, 153, 1);
  }

  /* 表格 */

  /**>uncoiler_elTableContainer*/
  .uncoiler_elTableContainer {
    margin-right: 0.5vw;
  }

  .uncoiler_elTableContainer .el-table {
    --el-table-border-color: transparent;
  }

  .el-table {
    // height: 100%;
    --el-table-row-hover-bg-color: unset;
    flex: 1;
    /* 填充剩余空间 */
    display: flex;
    flex-direction: column;
  }

  :deep(.el-table) {
    background-color: transparent;
    --el-table-border: none;
    color: white;

    :deep(.el-table__row:nth-child(odd)) {
      background-color: #223671;
    }

    .el-table__row {
      height: auto !important;
      line-height: 1.2;
    }

    .el-table__cell {
      padding: 2px 4px !important; // 横向纵向同时压缩

      .cell {
        font-size: 16px !important;
        transform: scale(0.85); // 字体缩放
        transform-origin: left; // 防止内容偏移
        white-space: nowrap; // 禁止换行
        // overflow: hidden;
        text-overflow: ellipsis; // 溢出显示...
      }
    }

    el-table__header-wrapper,
    .el-table__body-wrapper {
      min-width: 100% !important;
      width: auto !important;
    }
  }

  :deep(.el-table__inner-wrapper::before) {
    left: 0;
    bottom: 0;
    width: 100%;
    height: 0;
  }

  :deep(.el-table th),
  :deep(.el-table tr),
  :deep(.el-table td) {
    background-color: transparent;
  }

  :deep(.common_table .el-table__row:nth-child(odd)) {
    background-color: #223671;
  }

  // ... existing code ...
  :deep(.el-select) {
    width: 1rem;
    right: 1rem;
    background-color: transparent !important;
    color: #fff;
  }

  :deep(.el-select__wrapper) {
    background-color: transparent !important;
  }

  :deep(.el-input__wrapper) {
    background-color: #223671 !important;
    box-shadow: none !important;
  }

  :deep(.el-input__inner) {
    color: #fff !important;
  }

  :deep(.el-select-dropdown__item) {
    color: #fff !important;
  }

  :deep(.el-select-dropdown__item.hover, .el-select-dropdown__item:hover) {
    background-color: #2f59af !important;
  }

  :deep(.el-select-dropdown) {
    background-color: #223671 !important;
    border: 1px solid #2f59af !important;
  }

  :deep(.custom-date-picker.el-date-editor) {
    width: 260px !important;
    /* Match LayOutJudge */
    height: 28px;
    background-color: transparent !important;
    border: 1px solid #fff;
    box-shadow: none;
  }

  .pagination-container {
    margin-bottom: 20px;

    :deep(.el-pagination .el-pagination__sizes .el-select) {
      width: 140px;
    }
  }

  .reason-pagination-container,
  .team-pagination-container,
  .steel-grade-pagination-container {
    margin-top: 8px;
    margin-bottom: 8px;
    display: flex;
    justify-content: center;
    width: 100%;
    padding: 0 10px;

    :deep(.el-pagination) {
      --el-pagination-bg-color: transparent;
      --el-pagination-text-color: #c0c4cc;
      --el-pagination-button-disabled-bg-color: transparent;
      --el-pagination-button-bg-color: transparent;
      --el-pagination-hover-color: #409eff;
    }
  }

  :deep(.el-pager li) {
    border: 1px solid #2a5caa;
    margin: 0 3px;
    border-radius: 3px;
    min-width: 24px;
    height: 24px;
    line-height: 22px;
    font-size: 12px;
    background-color: #1890ff;
    border-color: #1890ff;
    color: #fff;
  }

  :deep(.el-pagination button) {
    border: 1px solid #2a5caa;
    margin: 0 3px;
    border-radius: 3px;
    min-width: 24px;
    height: 24px;
    padding: 0 6px;
  }

  :deep(.el-pagination button:disabled) {
    border-color: #2a5caa;
    opacity: 0.5;
  }

  :deep(.el-pagination__jump) {
    color: #c0c4cc;
    margin-left: 10px;
    font-size: 13px;
  }

  :deep(.el-pagination__jump .el-input__wrapper) {
    background: #0a1a3a !important;
    border: 1px solid #2a5caa !important;
    box-shadow: none !important;
    height: 24px;
    width: 40px;
    border-radius: 3px;
    padding: 0 3px;
  }

  :deep(.el-pagination__jump .el-input__inner) {
    color: #c0c4cc !important;
    height: 22px !important;
    line-height: 22px !important;
    text-align: center;
    font-size: 12px !important;
  }
  :deep(.el-pagination__total) {
    color: #c0c4cc;
    margin-right: 10px;
    font-size: 13px;
  }

  :deep(.el-pagination__sizes) {
    margin-right: 10px;
  }

  :deep(.el-pagination__sizes .el-select .el-input__wrapper) {
    background: #0a1a3a !important;
    border: 1px solid #2a5caa !important;
    box-shadow: none !important;
    height: 24px;
    width: 140px;
    border-radius: 3px;
    padding: 0 3px;
  }

  :deep(.el-pagination__sizes .el-select .el-input__inner) {
    color: #c0c4cc !important;
    height: 22px !important;
    line-height: 22px !important;
    font-size: 12px !important;
  }

  :deep(.el-pagination .el-select__caret) {
    color: #409eff;
  }

  :deep(
      .el-pagination,
      .team-pagination-container[data-v-4d662d9c] .el-pagination,
      .steel-grade-pagination-container[data-v-4d662d9c] .el-pagination
    ) {
    margin-left: 280px;
  }

  .card-body-yield {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin-top: 10px;
  }
  .yield-main-row {
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: flex-start;
  }
  .yield-main-col {
    width: 48%;
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  .card-title1 {
    color: #00cfff;
    font-size: 32px;
    font-weight: bold;
    margin-bottom: 8px;
  }
  .card-value1 {
    color: #1fe0ff;
    font-size: 38px;
    font-weight: bold;
    margin-bottom: 52px;
  }
  .yield-label-row {
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    margin-bottom: 2px;
  }
  .yield-label {
    color: #8ecfff;
    font-size: 18px;
  }
  .yield-value-row {
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    margin-bottom: 2px;
  }
  .yield-value {
    color: #fff;
    font-size: 22px;
  }
  .team-row-hover {
    background: linear-gradient(90deg, #2979ff 0%, #00eaff 100%) !important;
    color: #fff !important;
  }

  .right-content .label {
    margin-right: 18px;
    margin-left: 5px;
    white-space: nowrap;
    font-size: 12px;
    min-width: 80px; /* Ensure labels align */
    text-align: right;
  }

  .custom-input,
  .custom-select,
  :deep(.el-input__wrapper),
  :deep(.el-select__wrapper) {
    height: 28px;
    line-height: 28px;
    background-color: #0a1a3a !important;
    border: 1px solid #3a5a8a !important;
    border-radius: 3px !important;
    color: #c0c4cc !important;
    box-shadow: none !important;
    font-size: 12px !important;
  }
  :deep(.main-container .card-container[data-v-4d662d9c] .el-select) {
    width: 80px;
  }
  :deep(.reason-pagination-container[data-v-4d662d9c] .el-pagination__sizes) {
    margin-right: 10px;
  }

  :deep(.el-tabs--top) {
    --el-tabs-header-height: 35px;
  }
  :deep(.el-tabs__content) {
    overflow: visible;
  }
  :deep(.el-tabs--card > .el-tabs__header) {
    border: none; /* 去掉默认边框 */
    padding: 0;
    margin: 0 0 6px 0;
  }
  :deep(.el-tabs--card > .el-tabs__header .el-tabs__nav) {
    border: none; /* 去掉 nav 的边框 */
    box-shadow: none;
  }

  /* 用底部分隔线铺满宽度 */
  :deep(.el-tabs__nav-wrap::after) {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    content: '';
    height: 1px;
    background-color: #2a5caa; /* 与页面风格一致 */
    transform: none;
  }

  /* 激活态不突出边框，靠字体/背景表现 */
  :deep(.el-tabs--card > .el-tabs__header .el-tabs__item.is-active) {
    border: none !important;
  }

  :deep(.el-tabs--card > .el-tabs__header .el-tabs__item) {
    border: none !important;
    background: transparent !important;
    box-shadow: none !important;
    outline: 0 !important;
  }

  /* 激活态不突出边框，靠字体/背景表现 */
  :deep(.el-tabs--card > .el-tabs__header .el-tabs__item.is-active) {
    border: none !important;
    color: #00eaff !important; /* 激活状态使用亮蓝色 */
    font-weight: 600 !important; /* 增加字体粗细 */
  }

  :deep(.el-tabs--card > .el-tabs__header .el-tabs__item) {
    border: none !important;
    background: transparent !important;
    box-shadow: none !important;
    outline: 0 !important;
    color: #c0c4cc !important; /* 非激活状态使用较亮的灰色 */
    font-weight: 500 !important; /* 增加字体粗细 */
    transition: color 0.3s ease; /* 添加颜色过渡效果 */
  }

  /* 鼠标悬停效果 */
  :deep(.el-tabs--card > .el-tabs__header .el-tabs__item:hover) {
    color: #fff !important; /* 悬停时使用白色 */
  }

  /* 产品品类异常原因tab特殊样式 */
  :deep(.el-tabs--card > .el-tabs__header .el-tabs__item[aria-controls='pane-productReason']) {
    color: #e6f7ff !important; /* 产品品类异常原因tab使用更亮的颜色 */
  }

  :deep(.el-tabs--card > .el-tabs__header .el-tabs__item[aria-controls='pane-productReason']:hover) {
    color: #00eaff !important; /* 悬停时使用亮蓝色 */
  }

  :deep(.el-tabs--card > .el-tabs__header .el-tabs__item[aria-controls='pane-productReason'].is-active) {
    color: #00eaff !important; /* 激活状态使用亮蓝色 */
    font-weight: 700 !important; /* 激活状态字体更粗 */
  }

  .overText {
    white-space: nowrap; /* 禁止文本换行 */
    overflow: hidden; /* 隐藏超出容器的内容 */
    text-overflow: ellipsis; /* 超出部分显示... */
  }

  .lossAnalysis {
  }
</style>
